import gsap from 'gsap';

class LeafManager {
    constructor() {
        this.duration = 8000;
    }

    create(container) {
        this.active = true;
        this.lastTime = 0;

        const tick = (time) => {
            if (!this.active) return;

            if (!this.lastTime) {
                this.lastTime = time;
            }

            const elapsed = time - this.lastTime;
            const minInterval = this.duration * 0.5;
            const maxInterval = this.duration * 1.5;
            const nextDelay = minInterval + Math.random() * (maxInterval - minInterval);

            if (elapsed >= nextDelay) {
                this.render(container);
                this.lastTime = time;
            }

            this.frameId = requestAnimationFrame(tick);
        };

        this.frameId = requestAnimationFrame(tick);
    }

    destroy() {
        this.active = false;
        cancelAnimationFrame(this.frameId);
    }

    render(container) {
        const rect = container.getBoundingClientRect();

        let leaf = document.createElement("div");
        leaf.className = "leaf";
        container.appendChild(leaf);

        const fromX = Math.random() * (rect.width); // 减去叶子宽度避免跑出
        const toX = Math.random() * (rect.width);
        const fromY = 0;
        const toY = rect.height;

        gsap.to(leaf, {
            rotation: 90,
            duration: 1 + Math.random(),
            ease: "sine.inOut",
            repeat: -1,
            yoyo: true
        });

        // 下落动画
        gsap.fromTo(leaf, {
            x: fromX,
            y: fromY
        }, {
            x: toX,
            y: toY,
            duration: this.duration / 1000 + Math.random(),
            ease: "none",
            onComplete: () => leaf.remove()
        });
    }
}

export default new LeafManager();
